/**
 * # @param {object} config
 * - @param {object} api
 *  - @param {string} label 下拉框视图值
 *  - @param {string} value 下拉框model值
 *
 *  - @param {string} url
 *  - @param {string} dataField api返回数据的获取路径
 *  - @param {string} payload 向服务端发送的数据
 * */

export default {
    inject: ['getDataPathByPath', 'parseUrl'],
    props: {
        value: '',
        config: Object,
    },
    data() {
        this.options = this.config.options || null
        return {}
    },
    methods: {
        setEmptyOptions() {
            this.options = []
            this.$forceUpdate()
        },
        loadOptions(payload) {
            if (!this.config.async) return
            const api = this.config.api
            if (!(api && api.url && api.dataField)) return this.setEmptyOptions()
            this.http[api.url.method](this.parseUrl(api.url), payload || api.payload || null).then(res => {
                if (res.code == 200) {
                    this.options = this.getDataPathByPath(res.data, api.dataField)
                    this.$forceUpdate()
                } else {
                    this.setEmptyOptions()
                }
            })
        }
    },
    created() {
        this.loadOptions()
    },
}
